#!/usr/bin/python2.5
import logging
import wsgiref.handlers
import urllib

from google.appengine.ext import webapp
from google.appengine.api import urlfetch 
from google.appengine.api import mail

class ConvertUrlToPDF(webapp.RequestHandler):
    
    def get(self):
        #SERVICE_URL = "http://pdfmyurl.com?url="        
        SERVICE_URL = "http://api.joliprint.com/api/rest/url/print/s/pxdrill?url=" 
        SERVICE_FROM = "url2pdf@pxdrill.appspotmail.com"
        
        url = self.request.get('url')        
        recipient = self.request.get('email')
        fullUrl = SERVICE_URL + urllib.quote(url)
        #fullUrl = "http://api.joliprint.com/api/rest/url/print/s/my_app_name?url=http://bit.ly/fFZ8u0"
        
        document = None
        
        logging.debug("Fetching %s" % fullUrl)
        try:  
            result = urlfetch.fetch(url = fullUrl,
                                    method = "GET",
                                    deadline = 60) # 1 minute timeout. This is run in a task, so it could be more then 10 seconds (10 minutes is the offline limit)
                        
            if result.status_code != 200:
                message = "URL fetch failed with code %s, error %s" % (result.status_code, result.content)
                raise Exception(message)
            
            # all went well, create a mail message and attach result content
            logging.info("Converted %s into PDF" % url)            
            message_body = "Succesfully converted %s to PDF." % url
            subject = "Conversion results"
            
            document = result.content 
            
        except Exception, ex:
            logging.error("URL fetch failed. Error: %s" % ex)            
            message_body = "Error occured during conversion to PDF. Error: %s" % ex
            subject = "Error occured during conversion to PDF"
            
        logging.debug("Sending error message to %s: %s" % (recipient, message_body))
        
        message = mail.EmailMessage(sender=SERVICE_FROM,
                                    subject=subject)
        message.to = recipient
        message.body = message_body
        
        if document:
            message.attachments=[("ConversionResult.pdf", document)]
        
        message.send()   
   
        
def main():
    url_map = [('/queue/url2pdf', ConvertUrlToPDF)]
    
    application = webapp.WSGIApplication(url_map, debug=True)
    wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
    main()